package il.ac.bgu.cs.heuristics.core;

import il.ac.bgu.cs.heuristics.graph.types.IState;
import il.ac.bgu.cs.heuristics.graph.types.ISubstitution;
import il.ac.bgu.cs.heuristics.utils.CollectionUtils;

import java.util.Set;

public class ExtendenSearchNode {

	public ExtendenSearchNode		parentNodes		= null;
	public IState					subgoal			= null;
	public IState					effectVertex	= null;
	public int						hValue			= 0;
	public Set<ISubstitution>		reachedGoals	= null;
	public Set<ExtendenSearchNode>	actionGoalsList	= null;
	public boolean					reached			= false;

	public ExtendenSearchNode(ExtendenSearchNode parentNodes,
			IState effectVertex, IState subgoal) {
		this.actionGoalsList = CollectionUtils.newLinkedHashSet();
		this.parentNodes = parentNodes;
		this.subgoal = subgoal;
		this.effectVertex = effectVertex;
	}

	public int sonIsComplete(IState extednedGoal, int hValue) {
		this.hValue = Math.max(this.hValue, hValue);
		if (reachedGoals == null)
			reachedGoals = CollectionUtils.newLinkedHashSet();
		for (ISubstitution sub : extednedGoal.getSubstitutions()) {
			if (subgoal.contains(sub)) {
				reachedGoals.add(sub);
			}
		}
		for (ISubstitution sub : subgoal.getSubstitutions()) {
			if (!reachedGoals.contains(sub))
				return -1;
		}

		this.markAsReached();
		if (this.parentNodes == null)
			return this.hValue;
		return parentNodes.sonIsComplete(this.effectVertex, hValue);

	}

	private void markAsReached() {
		if (this.reached)
			return;
		this.reached = true;
		for (ExtendenSearchNode childnode : this.actionGoalsList) {
			childnode.markAsReached();
		}
	}
}
